//
//  MainViewController.m
//  ROSE
//
//  Created by 艾阳 on 2018/5/22.
//  Copyright © 2018年 HeNanZhongDunYunAn. All rights reserved.
//

#import "MainViewController.h"
#import "RoseLoginViewController.h"
#import "RoseCell.h"
#import "ZSIndexHeaderView.h"
#import "ZSIndexSecHeaderView.h"
#import "RoseModel.h"
#import "ZSMyRoseViewController.h"

@interface MainViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *mainCollectionView;
    ZSIndexHeaderView *indexHeaderView;
    ZSIndexSecHeaderView *indexSecHeaderView;
}
@property (nonatomic,strong) NSMutableArray<NSValue *>*elementsHight;
@property (nonatomic,strong) NSMutableArray<RoseModel *>*marketRoseArr;
@property (nonatomic,strong) NSMutableArray<RoseModel *>*myRoseArr;
//@property (nonatomic,strong) UICollectionView *collectionView;
@end

@implementation MainViewController

- (NSMutableArray<RoseModel *> *)marketRoseArr{
    if (!_marketRoseArr) {
        _marketRoseArr = [NSMutableArray new];
    }
    return _marketRoseArr;
}

- (NSMutableArray<RoseModel *> *)myRoseArr{
    if (!_myRoseArr) {
        _myRoseArr = [NSMutableArray new];
    }
    return _myRoseArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    RoseLoginViewController * loginVc = [[RoseLoginViewController alloc]init];
    UINavigationController * navigationVc = [[UINavigationController alloc]initWithRootViewController:loginVc];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tabBarController presentViewController:navigationVc animated:YES completion:nil];
    });
    
    self.title = @"首页";
    
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置collectionView滚动方向
    //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置headerView的尺寸大小
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
    //该方法也可以设置itemSize
//    110/150
    CGFloat width = (size_width-(15+35*2))/2;
    layout.itemSize =CGSizeMake(width, 80 + (384.0/517 * width));
    // 120 + (384.0/517 * width)
    
    //2.初始化collectionView
    mainCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.view addSubview:mainCollectionView];
    mainCollectionView.backgroundColor = [UIColor clearColor];
    
    //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [mainCollectionView registerClass:[RoseCell class] forCellWithReuseIdentifier:@"RoseCell"];
    
    //注册headerView  此处的ReuseIdentifier 必须和 supviewforsection 方法中 一致  均为reusableView
    [mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader0"];
    [mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader1"];
    
    //4.设置代理
    mainCollectionView.delegate = self;
    mainCollectionView.dataSource = self;
    
    indexHeaderView = [[ZSIndexHeaderView alloc] initWithFrame:(CGRectMake(0, 0, size_width, 224))];
    [indexHeaderView.moreButton addTarget:self action:@selector(myRoseMoreAction:) forControlEvents:(UIControlEventTouchUpInside)];
    indexSecHeaderView = [[ZSIndexSecHeaderView alloc] initWithFrame:(CGRectMake(0, 0, size_width, 70))];
    [indexSecHeaderView.moreButton addTarget:self action:@selector(gotoShop:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)myRoseMoreAction:(UIButton *)sender{
    ZSMyRoseViewController *myRoseVC = [ZSMyRoseViewController new];
    [self.navigationController pushViewController:myRoseVC animated:YES];
}

- (void)gotoShop:(UIButton *)sender;{
    [self.tabBarController setSelectedIndex:1];
}

static inline UIEdgeInsets sgm_safeAreaInset(UIView *view) {
    if (@available(iOS 11.0, *)) {
        return view.safeAreaInsets;
    }
    return UIEdgeInsetsZero;
}

static BOOL flag = NO;
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (flag==NO) {
        flag = YES;
        UIEdgeInsets ins = sgm_safeAreaInset(self.view);
        if (ins.top || ins.bottom) {
            NSLog(@"%.6f, %.6f", ins.top, ins.bottom);
            mainCollectionView.height = size_height-ins.top-ins.bottom;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([[LMJRequestManager sharedManager] IsLogin]){
        [self loadData];
    }
}

- (void)loadData{
    NSString *urlString = [NSString stringWithFormat:@"%@/usercenter/index", url_base];
    [[LMJRequestManager sharedManager] POST:urlString parameters:nil completion:^(LMJBaseResponse *response) {
        [self.marketRoseArr removeAllObjects];
        [self.myRoseArr removeAllObjects];
        if (!response.error) {
            NSString *errorcode = [NSString stringWithFormat:@"%@", response.responseObject[@"errorcode"]];
            if ([errorcode isEqualToString:@"000000"]) {
                //
                //NSLog(@"%@", response.responseObject);
                NSDictionary *dataobj = [NSDictionary dictionaryWithDictionary:response.responseObject[@"dataobj"]];
                NSArray *MARKETROSE = [NSArray arrayWithArray:dataobj[@"MARKETROSE"]];
                NSArray *MYROSE = [NSArray arrayWithArray:dataobj[@"MYROSE"]];
                NSDictionary *USER = [NSDictionary dictionaryWithDictionary:dataobj[@"USER"]];
                for (NSDictionary *temp in MARKETROSE) {
                    RoseModel *model = [RoseModel new];
                    [model setValuesForKeysWithDictionary:temp];
                    [self.marketRoseArr addObject:model];
                }
                for (NSDictionary *temp in MYROSE) {
                    RoseModel *model = [RoseModel new];
                    [model setValuesForKeysWithDictionary:temp];
                    [self.myRoseArr addObject:model];
                }
                ZSUserModel *model = [ZSUserModel shareInstance];
                [model setValuesForKeysWithDictionary:USER];
                [indexHeaderView setDataWithUserModel:model withNumber:self.myRoseArr.count];
            }else{
                NSLog(@"%@[%@]", response.responseObject, errorcode);
            }
        }else{
            NSLog(@"error:%@", response.error);
        }
        [mainCollectionView reloadData];
    }];
}

#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section==0) {
        if (self.myRoseArr.count>=2) {
            return 2;
        }
        return self.myRoseArr.count;
    }else{
        return self.marketRoseArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    RoseCell *cell = (RoseCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"RoseCell" forIndexPath:indexPath];
    
//    cell.name.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.section,(long)indexPath.row];
//    cell.imgView.backgroundColor = [UIColor RandomColor];
    if (indexPath.section==0) {
        if (indexPath.row<self.myRoseArr.count) {
            RoseModel *model = self.myRoseArr[indexPath.row];
            [cell setDataWithRoseModel:model];
        }
    }else{
        if (indexPath.row<self.marketRoseArr.count) {
            RoseModel *model = self.marketRoseArr[indexPath.row];
            [cell setDataWithRoseModel:model];
        }
    }
    return cell;
}

//设置每个item的尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return CGSizeMake(90, 130);
//}

//footer的size
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(10, 10);
//}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return CGSizeMake(size_width, 224);
    }else{
        return CGSizeMake(size_width, 70);
    }
    return CGSizeMake(10, 10);
    
}

//设置整个分区模块的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section==0) {
        return UIEdgeInsetsMake(0, 35, 0, 35);
    }else{
       return UIEdgeInsetsMake(0, 35, 25, 35);
    }
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}


//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader0" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor clearColor];
        if (![headerView.subviews containsObject:indexHeaderView]) {
            [headerView addSubview:indexHeaderView];
        }
        indexHeaderView.secHeaderLabel.text = @"我的玫瑰";
        return headerView;
    }else{
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader1" forIndexPath:indexPath];
        if (![headerView.subviews containsObject:indexSecHeaderView]) {
            [headerView addSubview:indexSecHeaderView];
        }
        indexSecHeaderView.titleLabel.text = @"玫瑰集市";
        return headerView;
    }
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    RoseCell *cell = (RoseCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSString *msg = cell.name.text;
    NSLog(@"%@",msg);
}


@end
